<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------


namespace app\operation\model;

use think\Model as ThinkModel;

/**
 * 优惠券模型
 * @package app\operation\model
 */
class Coupon extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = '__OPERATION_COUPON__';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    
    
    /**
     * 获取商品详情可用优惠券
     * @author 晓风<215628355@qq.com>
     */
    public static function getGoodsInfoNew(int $goods_id,int $cid , int $user_id = 0, int $limit = 10){        
        $nowTime = time();
        $map[] = ['method', 'eq', 2];
        $map[] = ['status', 'eq', 1];
        $map[] = ['is_delete', 'eq', 0];
        $map[] = ['start_time', '<=', $nowTime];
        $map[] = ['end_time', '>=', $nowTime];
        $map[] = ['last_stock', 'gt', 0];    
        $map[] = ['goods_id', 'in',[$goods_id,0] ];
        $pids = \app\goods\model\Category::getParentsId($cid);
        $pids[] = 0;
        $map[] = ['cid', 'in', array_unique($pids)];       
        $lists  =  self::where($map)->order("money desc")->field('id,name,money,min_order_money,end_time,last_stock,content')->limit($limit)->select();      
        foreach ($lists as &$v) {                  
            $v['end_time'] = date('Y-m-d H:i:s', $v['end_time']);     
            if ($user_id) {
                $v['is_receive'] = CouponRecord::checkCoupon( $user_id, $v['id']);
            }else{
                $v['is_receive']  = 0;
            }
        }    
        unset($v);
        return $lists;
    }
    
     /**
     * 结束/删除优惠券
     * @param array $ids
     */
    public static function delIds($ids){
        if(!is_array($ids)){
            $ids = explode(",",$ids);
        }       
        CouponRecord::unsetTime();
        foreach($ids as $id){     
            //检查会员是否持有该优惠券，以及是否使用
            $count =  CouponRecord::where("cid",$id)->where("status","in",[1,2,3])->count(); 
            if($count <=0){
                self::where("id",$id)->delete();  
            }else{                
                self::where("id",$id)->update([
                    "status"=>0,
                    "is_delete"=>1
                ]);  
            }  
            //若会员优惠券过期或失效，则删除之
            CouponRecord::where("cid",$id)->where("status","not in",[1,2,3])->delete();
        }
        return true;              
    }

}